package cn.com.duiba.millionaire.center.biz.service.impl;

import cn.com.duiba.millionaire.center.api.msg.LoadReliveCardMsg;
import cn.com.duiba.millionaire.center.biz.service.LoadReLiveCardService;
import cn.com.duiba.millionaire.center.biz.service.RenascenceRecordService;
import cn.com.duiba.millionaire.center.biz.tool.GZIPCompressUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by sty on 2/1/18.
 */
@Service
public class LoadReLiveCardServiceImpl implements LoadReLiveCardService {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoadReLiveCardServiceImpl.class);

    @Resource(name = "redisTemplate")
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private RenascenceRecordService renascenceRecordService;

    @Override
    public void handle(byte[] msg) {
        if (!uniqueCheck(msg)) {
            return;
        }
        String src = GZIPCompressUtil.ungzip(msg);
        List<LoadReliveCardMsg> msgList = JSONObject.parseArray(src, LoadReliveCardMsg.class);
        if (CollectionUtils.isEmpty(msgList)) {
            LOGGER.warn("list is empty!");
            return;
        }
        renascenceRecordService.batchLoadFromDatabase(msgList);
    }

    private boolean uniqueCheck(byte[] msg) {
        String md5 = DigestUtils.md5Hex(msg);
        Boolean ret = redisTemplate.opsForValue().setIfAbsent(md5, "0");
        if (!ret) {
            return false;
        }
        redisTemplate.expire(md5, 2, TimeUnit.HOURS);
        return true;
    }
}
